define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'template', 'tagsinput', 'autocomplete'], function ($, undefined, Backend, Table, Form, Template) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'yunfood/food/main/index' + location.search,
                    add_url: 'yunfood/food/main/add',
                    edit_url: 'yunfood/food/main/edit',
                    del_url: 'yunfood/food/main/del',
                    multi_url: 'yunfood/food/main/multi',
                }
            });

            var table = $("#table");

            // 初始化表格template
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                columns: [
                    [
                        // 该列为复选框字段,如果后台的返回state值将会默认选中
                        {
                            field: 'state',
                            checkbox: true
                        },
                        // sortable为是否排序,operate为搜索时的操作符,visible表示是否可见
                        {
                            field: 'id',
                            title: 'ID',
                            sortable: true,
                            operate: false
                        },
                        {
                            field: 'shopId',
                            title: __('限定门店'),
                            searchList: Config.shopList,
                            formatter: function (value, row, index) {
                                return row.shop_text;
                            },
                        },
                        // 模糊搜索
                        {
                            field: 'name',
                            title: __('名称'),
                            operate: 'LIKE %...%',
                            placeholder: '模糊搜索',
                        },
                        {
                            field: 'cover_url',
                            title: __('封面'),
                            operate: false,
                            formatter: Table.api.formatter.image
                        },
                        {
                            field: 'category_id',
                            title: __('分类'),
                            searchList: Config.categoryList,
                            formatter: function (value, row, index) {
                                if (!value) {
                                    return '无';
                                }
                                return row.category_data ? row.category_data.name : '已删除';
                            }
                        },
                        {
                            field: 'multi_spec',
                            title: __('多规格'),
                            searchList: {0: '否', 1: '是'},
                            formatter: Table.api.formatter.normal
                        },
                        {
                            field: 'market_price',
                            title: __('原价'),
                            sortable: true,
                            operate: false,
                        },
                        {
                            field: 'price',
                            title: __('售价'),
                            sortable: true,
                            operate: false,
                        },
                        {
                            field: 'count_left',
                            title: __('库存'),
                            sortable: true,
                            operate: false,
                        },
                        {
                            field: 'count_sale',
                            title: __('销量'),
                            sortable: true,
                            operate: false,
                        },
                        {
                            field: 'note',
                            title: __('备注'),
                            operate: 'LIKE %...%',
                            placeholder: '模糊搜索',
                        },
                        {
                            field: 'weight',
                            title: __('权重'),
                            sortable: true,
                            operate: false,
                        },
                        {
                            field: 'status',
                            title: __('Status'),
                            searchList: Config.statusList,
                            formatter: Table.api.formatter.status
                        },
                        {
                            field: 'updated_at',
                            title: __('Update time'),
                            sortable: true,
                            operate: false,
                            formatter: Table.api.formatter.datetime,
                        },
                        {
                            field: 'created_at',
                            title: __('Create time'),
                            sortable: true,
                            formatter: Table.api.formatter.datetime,
                            operate: 'RANGE',
                            addclass: 'datetimerange'
                        },
                        // 操作栏,默认有编辑、删除或排序按钮,可自定义配置buttons来扩展按钮
                        {
                            field: 'operate',
                            width: '150px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'order',
                                    text: __('订单'),
                                    title: function (row) {
                                        return __('相关订单') + ' - ' + row.name;
                                    },
                                    classname: 'btn btn-xs btn-info btn-dialog',
                                    visible: function (row) {
                                        return row.count_sell > 0;
                                    },
                                    extend: 'data-area=\'["100%","100%"]\'',
                                    icon: 'fa fa-list',
                                    url: function (row) {
                                        return 'yunfood/order/main/index?goods_id=' + row.id;
                                    },
                                },
                            ],
                            formatter: function (value, row, index) {
                                var that = $.extend({},this);
                                var table = $(this.table).clone(true);
                                if (row.mute_operate) {
                                    $(table).data('operate-edit', null);
                                    $(table).data('operate-del', null);
                                }
                                that.table = table;
                                return Table.api.formatter.operate.call(that, value, row, index);
                            }
                        },
                    ],
                ],
                // 快捷搜索,这里可在控制器定义快捷搜索的字段
                search: false,
                // 启用普通表单搜索
                commonSearch: true,
                // 显示切换视图（table/card）按钮
                showToggle: false,
                // 显示导出按钮
                showExport: true,
                // 启用跨页选择
                maintainSelected: true,
                // 启用固定列
                fixedColumns: true,
                // 固定右侧列数
                fixedRightNumber: 1,
                // 可以控制是否默认显示搜索单表,false则隐藏,默认为false
                searchFormVisible: true,
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

            // 弹窗大小
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                $('.btn-editone').data('area', ['95%', '95%']);
            });
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        detail: function () {
        },
        api: {
            bindevent: function () {
                Template.helper("Fast", Fast);

                // 多规格
                $(document).on("change", "#c-multi_spec", function () {
                    var value = $(this).val();
                    console.log("multi_spec change", value);
                    if (value === "1") {
                        $("#box-sku").removeClass("hide");
                        $("#box-price").addClass("hide");
                        $("#box-count_left").addClass("hide");
                    } else {
                        $("#box-sku").addClass("hide");
                        $("#box-price").removeClass("hide");
                        $("#box-count_left").removeClass("hide");
                    }
                });
                $('#c-multi_spec').trigger('change');

                // 选择规格
                $(".choose-spec").on('click', function () {
                    var url = "yunfood/food/param/index";
                    parent.Fast.api.open(url + '?type=spec&choose=1', __('Choose'), {
                        area: ['80%', '800px'],
                        callback: function (data) {
                            console.log('choose data', data);
                            var $specData = $('#c-specData');
                            var skuList = JSON.parse($specData.val());
                            $.each(data.chooseItems, function (i, v) {
                                skuList.push({
                                    name: v.name,
                                    items: v.items
                                })
                            });
                            console.log('skuList', skuList);
                            $specData.val(JSON.stringify(skuList));
                            $("#c-specData-table").trigger("fa.event.refreshfieldlist");
                        }
                    });
                    return false;
                });

                // 菜品规格
                $(document).on("fa.event.appendfieldlist", '[data-name="row[specData]"] .btn-append', function (e, obj) {
                    console.log('specData append', e, obj);
                    Form.events.tagsinput(obj);
                    updateSkuItems();  // 更新sku

                    $(obj).on('itemAdded', function (event) {
                        console.log('itemAdded')
                        updateSkuItems();  // 更新sku

                    }).on('itemRemoved', function (event) {
                        console.log('itemRemoved')
                        updateSkuItems();  // 更新sku
                    });
                });
                $('#c-specData-table').on('click', '.btn-remove', function () {
                    setTimeout(function () {
                        updateSkuItems();  // 更新sku
                    }, 50);
                }).on('click', '.btn-save-spec', function () {
                    console.log('save spec');
                    var index = $(this).parents('.form-inline').index() - 1;
                    var specList = JSON.parse($('#c-specData').val());
                    var spec = specList[index];
                    if (!spec) {
                        Toastr.error("名称和规格还未填写");
                        return;
                    }
                    if (!spec.name) {
                        Toastr.error("名称不能为空");
                        return;
                    }
                    if (!spec.items) {
                        Toastr.error("规格不能为空");
                        return;
                    }
                    Layer.confirm(__('确认保存当前规格到通用规格？'), {
                        title: __('系统提示'),
                        btn: [__('保存'), __('取消')]
                    }, function (index) {
                        Fast.api.ajax({
                            url: 'yunfood/food/param/save',
                            data: {
                                type: 'spec',
                                name: spec.name,
                                items: spec.items
                            },
                        }, function (res) {
                            console.log('spec add', res);
                            return true;
                        });
                        layer.close(index);
                    }, function (index) {
                        layer.close(index);
                    });
                }).on('change', '.c-sku-name', function (e) {
                    setTimeout(function () {
                        updateSkuItems();  // 更新sku条目
                    }, 50);
                });

                // 更新sku条目
                var updateSkuItems = function () {
                    var $skuTable = $("#c-skuData-table");
                    var $specData = $('#c-specData');
                    var $skuData = $('#c-skuData');
                    var specList = JSON.parse($specData.val());
                    var skuList = JSON.parse($skuData.val());
                    var skuMap = {};
                    $.each(skuList, function (i, v) {
                        skuMap[v.spec_text] = v;
                    });
                    $('#sku-head .sku-tit').remove();  // 清空head

                    var totalCount = 0, skuCount = 0;
                    if (specList.length > 0) {
                        totalCount = 1;
                        $.each(specList, function (i, v) {
                            if (v.name && v.items) {
                                skuCount++;
                                var names = v.items.split(',');
                                totalCount *= names.length;
                                $('#sku-mid').before('<th class="sku-tit">' + v.name + '</th>');  // 增加head
                            }
                        });
                        if (skuCount === 0) {
                            totalCount = 0;
                        }
                    }
                    $('#sku-blank').attr('colspan', skuCount + 1);  // head偏移

                    skuList = [];
                    for (i = 0; i < totalCount; i++) {
                        var rowData = [], rowCount = 1, specNames = [];
                        for (var j = 0; j < specList.length; j++) {
                            if (!specList[j].name || !specList[j].items) {
                                continue;
                            }
                            var skuItems = specList[j].items.split(',');
                            rowCount *= skuItems.length;
                            var middle = totalCount / rowCount;
                            var point = (i / middle) % skuItems.length;
                            // console.log('i % middle', i, middle, i % middle)
                            if (0 === (i % middle)) {
                                rowData.push({
                                    rowspan: middle,
                                    name: skuItems[point],
                                });
                            }
                            specNames.push(skuItems[parseInt(point.toString())]);
                        }

                        var specText = specNames.join(',');
                        var skuItem = skuMap[specText] || {
                            id: 0,
                            spec_text: specText,
                            cover_url: '',
                            market_price: 0,
                            price: 0,
                            count_left: 0,
                            status: 1
                        }
                        skuItem.spec_items = rowData;
                        skuItem.spec_data = JSON.stringify(rowData);
                        skuList.push(skuItem);
                    }
                    console.log('skuItemList', skuList);
                    if (skuList.length > 0) {
                        $skuTable.removeClass("hide");
                    } else {
                        $skuTable.addClass("hide");
                    }
                    $skuData.val(JSON.stringify(skuList));
                    $skuTable.trigger("fa.event.refreshfieldlist");
                };
                $(document).on("fa.event.appendfieldlist", '[data-name="row[skuData]"] .btn-append', function (e, obj) {
                    console.log('skuData append')
                    Form.events.faupload(obj);
                    Form.events.faselect(obj);

                    // 图片上传成功事件
                    // $(".upload-image", obj).data("upload-success", function (data) {
                    //     console.log('upload-success', data);
                    //     $(this).parent('td').find('.c-sku-item-cover-preview').attr('src', Fast.api.cdnurl(data.url));
                    // });

                    // 图片变更事件
                    $(obj).on('change', '.c-sku-item-cover', function (e) {
                        console.log('c-sku-item-cover change', $(this).val());
                        $(this).parent('td').find('.c-sku-item-cover-preview').attr('src', Fast.api.cdnurl($(this).val()));
                    });

                    // 图片点击事件
                    $(obj).on('click', '.c-sku-item-cover-preview', function (e) {
                        console.log('c-sku-item-cover-preview click');
                        $(this).parent('td').find('.c-sku-item-cover').val('').trigger("change");
                    });
                });
                $('#c-skuData-table').on('click', '.btn-multi-set', function () {
                    console.log('multi set');

                    // 批量更新
                    var multiMarketPrice = $('#multi-market-price').val();
                    var multiPrice = $('#multi-price').val();
                    var multiCountLeft = $('#multi-count-left').val();
                    var $skuData = $('#c-skuData');
                    console.log('skuItemList before', $skuData.val());
                    var skuItemList = JSON.parse($skuData.val());
                    $.each(skuItemList, function (i, v) {
                        if (multiMarketPrice) {
                            v.market_price = multiMarketPrice;
                        }
                        if (multiPrice) {
                            v.price = multiPrice;
                        }
                        if (multiCountLeft) {
                            v.count_left = multiCountLeft;
                        }
                        v.spec_items = JSON.parse(v.spec_data);
                    });
                    $skuData.val(JSON.stringify(skuItemList));
                    console.log('skuItemList after', JSON.stringify(skuItemList));
                    $("#c-skuData-table").trigger("fa.event.refreshfieldlist");
                })

                Form.api.bindevent($("form[role=form]"), null, null, function () {
                    var multiSpec = $("#c-multi_spec").val();
                    var specData = $("#c-specData").val();
                    console.log('before submit', multiSpec, specData);
                    if (multiSpec === '1') {
                        specData = JSON.parse(specData);
                        if (specData.length === 0) {
                            Toastr.error("规格不能为空");
                            return false;
                        }
                    }

                    return true;
                });
            },
            formatter: {  // 渲染的方法
            },
            events: { // 绑定事件的方法
            }
        }
    };
    return Controller;
});
